<template>
  <div :id="id" style="width:100%;height:100%" class="htmlGadget">
    <Portal to="right-disable"
            v-loading="loading" style="width:100%;height:100%"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  style="width:100%;height: 100%;border:0">

        <div style="height: 100%;">
          <el-card shadow="hover"
                   class="content-wrapper"
                   style="width:100%;height: 100%;border:0">
             <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">

              <MoreMenu :slicer='slicer'
                        :fitToHeight='fitToHeight'
                         v-if="!isQueryModel"
                        :gadgetId='id'
                        :gadgetType='gadgetInfo.com'
                        :widgetName="widgetName"
                        :businessType="gadgetInfo.businessType"
                        :id="gadgetInfo.id"
                        @showQueryModel="showQueryModel"
                        @fullScreen="fullScreen" />
              <!-- </div> -->
            </div>
            <div v-if="gadgetSetting.isTextEdit"
                 v-show="gadgetSetting.isTextEdit"
                 v-html="gadgetSetting.htmlValue"
                 class="content el-card__body html_box"
                 :class='randomId'
                 ref="html_box"
                 style="height:100%;"
                 :style="gadgetSetting.isCenter?'justify-content:center;':''">
            </div>
            <div v-else
                 class="ql-container ql-snow">
              <div v-html="gadgetSetting.htmlValue"
                   class="content ql-editor"
                   style="height:100%;padding:0 20px;"
                   :style="gadgetSetting.isCenter?'justify-content:center;':''">
              </div>
            </div>
            <div v-if="!gadgetSetting.htmlValue"
                 class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
            </div>

          </el-card>
        </div>
        <!-- <Lastupdatetime v-if="currentTime"
                      :currentTime="currentTime"></Lastupdatetime> -->
      </DashboardInterceptConsumer>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :queryId="queryId"
                  :slicer="slicer"
                  ref="drill-through"
                  :widgetName='widgetName' />
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
// import model from '@/components/gadget/query-model/query-model.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import { replaceUserDateFormat } from '@/utils/formatEmail.js'
// import { debounce } from 'lodash'
export default ({
  inject: {isQueryModel:{default:false}},
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: {
    Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model')
  },
  data: function () {
    return {
      datesource: '',
      currentTime: null,
      gadgetSetting: {},
      loading: false,
      autoRefresh: false,
      randomId: 'rid' + this._.random(1, 999),
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'htmleditorgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'htmleditorgadget' }).gadgetSetting
        }
      },
      queryId: '',
      queryDrillthrough: {},
      widgetName: '',
      conditionFormat: [],
      // noDataImageUrl: 'https://oss.mspbots.ai/app/gadget/card-number-title-default.png'
      comFormatData: null,
      valueFieldsWidth: null,
      queryFields:[]
    }
  },
  beforeCreate () {
    // this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    Vue['_this'] = this
    this.subscribeMessage('runReport', this.query)
    this.gadgetHeight = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.availHeight-100 :this.pageFromType === 'report' ? (this.gadgetInfo.h * this.rolHeight) - 20 : this.pageFrom === 'reportLayout' ? ((this.gadgetInfo.h * 20) - 20) : ((this.gadgetInfo.h * 23) - 20)
    this.gadgetWidth = this.pageFrom === 'reportLayoutFullScreen' ? window.screen.width :(this.gadgetInfo.w * 7) * 19
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  updated () {
    if (document.querySelector('.' + this.randomId + '>iframe')) {
      this.$nextTick(() => {
        this.setHeight()
      })
    }
  },
  methods: {
    setHeight () {
      if (document.querySelector('.' + this.randomId + '>iframe')) {
        document.querySelector('.' + this.randomId + '>iframe').style.height = (this.gadgetHeight - 20) + 'px'
      }
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetWidth = newWPx
      this.gadgetHeight = this.pageFromType === 'report'  ? (newH * this.rolHeight) -20 :(newH * 20) - 20
      this.setHeight()
    },
    query (e) {
      if (e !== 'auto') {
        this.loading = true
      }
      this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      this.queryModelDefaultSetting.dataInfo.gadgetSetting = {}
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
        _self.verifyHasData(res)
        if (res.data && res.data.length > 0) {
          _self.queryFields = res.selectFields
          this.currentTime = new Date()
          res.data = res.data.map(item => {
               Object.keys(item).forEach(ii => {
               item[ii] = this.setFormatFunctionForChart(this.queryFields, item[ii], ii) 
              })
              return item
            })
        }
        if (res.config) {
          try {
            // eslint-disable-next-line
            res.config.htmlValue = res.config.htmlValue.replace(/\{.*?\}/g,val=>{
              
              val = val.match(/\{(.*?)\}/)[1]
              if(val === 'CurrentDate') {
                return `{CurrentDate}`
              }else {
                return res&&res.data&&res.data[0]&&res.data[0][val]
              }
            })
            res.config.htmlValue = replaceUserDateFormat(res.config.htmlValue)
          } catch (error) {
            
          }
          _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
        }
        if (res.name) {
          _self.widgetName = res.name
        } else {
          _self.widgetName = _self.gadgetSetting.headerTitle
        }
     
      }).catch((error) => {
        this.isHasData = false
        this.loading = false
        if (error.response && error.response.status === 504) {
          this.errorStatus = '504'
          this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
        }
      }).finally(() => {
        this.autoRefreshQuery(e)
        this.updateGadgetLoadingStatus(!this.loading)
      })
    }
  }
})
</script>
<style lang="scss" scoped>
.content-wrapper {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 40%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
::v-deep .ql-container {
  height: 100% !important;
}
.el-card ::v-deep .el-card__body {
  height: 100%;
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.content {
  display: flex;
  /* justify-content: space-between; */
  flex-direction: column;
  height: 100%;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.main {
  display: flex;
  /* justify-content: space-around; */
  text-align: center;
  /* margin-top: 35px; */
  padding: 5px 0 !important;
  /*height: 85px;*/
}

.footer {
  text-align: left;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  z-index: 9999;
  /* padding: 10px 16px; */
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
.html_box {
  position: relative;
  overflow: hidden;
  padding-top: 56.25%;
}
</style>
